package com.uhuibao.tmall.apis.job;

import com.uhuibao.tmall.api.service.IOrderService;
import com.uhuibao.tmall.common.utils.MD5;
import com.uhuibao.tmall.common.utils.OkHttpClientUtils;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

/**
 * 订单查询，然后通知天猫
 */
@Component
public class OrderSchedule {

    public static Logger logger = LoggerFactory.getLogger(OrderSchedule.class);

    @Autowired
    private IOrderService orderService;

    @Autowired
    public RedisTemplate redisTemplate;

    @Value("${tmall.tmallSecret}")
    private String tmallSecret;

    @Value("${tmall.sellerId}")
    private Long sellerId;

    private Integer time = 0;

    @Async
    @Scheduled(cron = "*/5 * * * * ?")   //定时器定义，设置执行时间
    public void process() throws UnsupportedEncodingException, NoSuchAlgorithmException {

        //查询出当天的订单、然后跟Redis状态比对，如果是不一致的  就通知天猫
        List<Map<String, Object>> orderList = orderService.getChainOrderList();
        logger.info("【总共条数】：{}", orderList.size());
        if (orderList != null && !orderList.isEmpty()){
            for (Map<String, Object> resultMap : orderList) {
                String traceNo = resultMap.get("TRACE_NO").toString();
                String coopOrderNo = resultMap.get("ORDER_NO").toString();
                String tmallNotifyUrl = resultMap.get("TMALL_NOTIFY_URL").toString();

                //0创建中1已创建2成功3失败4接口异常失败
                String coopOrderStatus = null;
                String errDesc = null;
                int uhbOrderStatus = Integer.parseInt((String) resultMap.get("STATUS"));
                if (uhbOrderStatus < 2) {
                    coopOrderStatus = "UNDERWAY";
                    errDesc = "订单充值中";
                }
                if (uhbOrderStatus == 2) {
                    coopOrderStatus = "SUCCESS";
                    errDesc = "订单充值成功";
                }
                if (uhbOrderStatus > 2) {
                    coopOrderStatus = "FAILED";
                    errDesc = "订单充值失败";
                }

                //推送回调
                logger.info("【推送给天猫】：{} \r\n", coopOrderNo);

                TreeMap<String, Object> allParams = new TreeMap<>();
                long ts = System.currentTimeMillis();
                logger.info("时间戳："+ts);
                allParams.put("bizType", "ECARD_FLOWCHARGE");
                allParams.put("coopOrderNo", coopOrderNo);
                allParams.put("coopOrderStatus", coopOrderStatus);
                allParams.put("errCode", coopOrderStatus);
                allParams.put("errDesc", errDesc);
                allParams.put("supplierId", sellerId);
                allParams.put("tbOrderNo", traceNo);
                allParams.put("ts", ts);
                StringBuilder stringBuilder = new StringBuilder();
                for (Map.Entry<String, Object> entry : allParams.entrySet()) {
                    stringBuilder.append(entry.getKey()).append(entry.getValue());
                }
                // 打印拼接后的参数字符串
                String concatenatedParams = stringBuilder.toString() + tmallSecret;
                logger.info("【拼接后的参数字符串】：{} .", concatenatedParams);

                String mySign = MD5.encryptMD5(concatenatedParams);

                String url = tmallNotifyUrl + "?bizType=ECARD_FLOWCHARGE&coopOrderNo=" + coopOrderNo + "&coopOrderStatus=" + coopOrderStatus + "&errCode=" + coopOrderStatus + "&errDesc=" + errDesc + "&supplierId=" + sellerId + "&tbOrderNo=" + traceNo + "&ts=" + ts + "&sign=" + mySign;
                Response ret = OkHttpClientUtils.getInstance().getData(url);
                logger.info("【回调接口响应】：{} \r\n", ret);

                orderService.updateOrderTmallIsCallback(coopOrderNo);
            }
        }

    }
}
